import request from '@/utils/request'
import * as qiniu from 'qiniu-js'
// banner
export function getBannerInfo() {
  return request({
    url: '/api/banner/list',
    method: 'get'
  })
}
export function deleteBanner(data) {
  return request({
    url: '/api/banner/deleteById?id=' + data.id,
    method: 'get'
  })
}
export function addBanner(data) {
  return request({
    url: '/api/banner/save',
    method: 'post',
    data
  })
}
// 上传到七牛云
export function getQniuToken(data) {
  return request({
    url: '/api/kodo/token',
    method: 'post',
    data
  })
}

// export async function uploadFile (e){
//   console.log('e :>> ', e);
//    const tokenData = await getQiniuToken();
//    let qiniuUpToken = tokenData.data.token
//    //文件对象
//    var files = e.target.files
//    files = this.sortFile(files)
//    const uploadMain = (file)=>{
//        return  new Promise((resolve, reject) => {
//            let rawFileName = file.name;
//            // 很重要 自定义文件名字
//            let newFileName = new Date().getTime() + "_" + rawFileName;
//            var observable = qiniu.upload(file, newFileName, qiniuUpToken)
//            //设置监听者对象
//            var observer = {
//                next(res) {
//                console.log('总大小=>' + res.total.size + ',当前已上传大小=>' + res.total.loaded + ',当前进度=>' + res.total.percent)
//                },
//                error(err) {
//                    reject()
//                },
//                complete(res) {
//                    resolve(res)
//                }
//            }
//            subscription = observable.subscribe(observer)
//        })
//    }
//    if (!files.length) return

//    if (qiniuUpToken) {
//        //提交文件到服务器
//        for (var i = 0; i < files.length; i++) {
//           // await uploadMain(files[i])
//        }
//    }

// }
export async function uploadFile(params) {
  console.log('params :>> ', params);
  return new Promise((resolve, reject) => {
    const config = { useCdnDomain: true, region: qiniu.region.z0 }
    const putExtra = { fname: params.file, params: {}, mimeType: null }
    // 开始上传  token 需要找后端获取(单独的方法)
    getQniuToken().then(res => {
      const upToken = res.data.token
      const baseUrl = '' // res.data.buckethostname
      const headers = qiniu.getHeadersForMkFile(upToken)
      // file 是获取到的文件对象
      // key 是文件名字，传null将使用hash值来当作文件名

      const rawFileName = params.file.name
      const index = rawFileName.lastIndexOf('.')
      // 很重要 自定义文件名字
      const newFileName = 'tmpfile/' + uuid() + rawFileName.substr(index, rawFileName.length - index + 1)
      const observable = qiniu.upload(params.file, newFileName, upToken, headers, putExtra, config)
      this.subscription = observable.subscribe(observe)
    })
    const observe = {
      next(res) {
        // console.log('已上传大小，单位为字节：' + res.total.loaded)
        // console.log('本次上传的总量控制信息，单位为字节：' + res.total.size)
        // console.log('当前上传进度，范围：0～100：' + res.total.percent);
        console.log(res)
      },
      error(err) {
        // console.log(err.code)
        // console.log(err.message)
        // console.log(err.isRequestError)
        // console.log(err.reqId)
        console.log(err)
      },
      /* 完成后的操作*/
      complete(res) {
        // 上传成功以后会返回key 和 hash  key就是文件名了！
        const upUrl = 'http://att.xinshengyazzy.com/' + res.key
        const data = {
          data: [upUrl]
        }
        resolve(data)
        // let fileUrl =baseUrl + '/' + res.key
      }
    }
  })
}
export function uuid(length = 36) {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < length; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}
